package com.example.demo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.LogoPosition;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiBoundSearchOption;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private MapView mMapView = null;
    private LocationClient mLocationClient;
    private static final String TAG = "MainActivity";
    private PoiSearch poiSearch;
    private LatLng mLatLng;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取地图控件引用
        mMapView =  (MapView) findViewById(R.id.bmapView);

        //隐藏地图标注，只显示道路信息，默认显示地图标注
//        mMapView.getMap().showMapPoi(false);

        //直接缩放至缩放级别16
        mMapView.getMap().setMapStatus(MapStatusUpdateFactory.zoomTo(16));

        mMapView.getMap().setOnMapLongClickListener(new BaiduMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {

                //构建Marker图标
                BitmapDescriptor bitmap = BitmapDescriptorFactory
                        .fromResource(R.drawable.marker_custom);
                //构建MarkerOption，用于在地图上添加Marker
                OverlayOptions option = new MarkerOptions()
                        .position(latLng) //必传参数
                        .icon(bitmap) //必传参数
                        .draggable(true)
                //设置平贴地图，在地图中双指下拉查看效果
                        .flat(true)
                        .alpha(0.5f);
                //在地图上添加Marker，并显示
                mMapView.getMap().addOverlay(option);
            }
        });

        mMapView.getMap().setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Log.e(TAG,latLng.toString());
                mLatLng=latLng;
                Toast.makeText(MainActivity.this,"单击坐标维度："+latLng.latitude+",经度："+latLng.longitude,Toast.LENGTH_SHORT).show();

               
                //构建折线点坐标
                LatLng p1 = latLng;
                LatLng p2 = new LatLng(p1.latitude-0.004, p1.longitude);
                LatLng p3 = new LatLng(p1.latitude-0.004, p1.longitude+0.004);
                LatLng p4 = new LatLng(p1.latitude, p1.longitude+0.004);
                List<LatLng> points = new ArrayList<LatLng>();
                points.add(p1);
                points.add(p2);
                points.add(p3);
                points.add(p4);
                points.add(p1);

                //设置折线的属性
                OverlayOptions mOverlayOptions = new PolylineOptions()
                        .width(10)
                        .color(0xAAFF0000)
                        .points(points);
                //在地图上绘制折线
                //mPloyline 折线对象
                Overlay mPolyline = mMapView.getMap().addOverlay(mOverlayOptions);

            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });


        mMapView.getMap().setOnMapDoubleClickListener(new BaiduMap.OnMapDoubleClickListener() {
            @Override
            public void onMapDoubleClick(LatLng latLng) {
                Toast.makeText(MainActivity.this,"双击坐标维度："+latLng.latitude+",经度："+latLng.longitude,Toast.LENGTH_SHORT).show();
                drawCircle(latLng);
                drawText(latLng);
//                showInfoWindow(latLng);
            }
        });

        mMapView.getMap().setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Toast.makeText(MainActivity.this,"markOnClick......",Toast.LENGTH_SHORT).show();
//                Toast.makeText(MainActivity.this,marker.getExtraInfo().getInt("index"),Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        poiSearch = PoiSearch.newInstance();
        poiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                Log.e(TAG,"onGetPoiResult"+poiResult.getAllPoi().size());
                for(int i=0;i<poiResult.getAllPoi().size();i++){
                    PoiInfo poiInfo=poiResult.getAllPoi().get(i);
                    Log.e(TAG,poiInfo.getName()+"  "+poiInfo.getAddress()+"  uid="+poiInfo.getUid());
                }

                PoiOverlay poiOverlay=new PoiOverlay(mMapView.getMap());
                poiOverlay.setData(poiResult);

                poiOverlay.addToMap();
                poiOverlay.zoomToSpan();
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

            }

            @Override
            public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
                Log.e(TAG,poiDetailSearchResult.getPoiDetailInfoList().get(0).getName()+"   "+poiDetailSearchResult.getPoiDetailInfoList().get(0).getTelephone());
            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }
        });


        findViewById(R.id.btn_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                poiSearch.searchInCity(new PoiCitySearchOption().city("广州").keyword("医院"));
            }
        });

        findViewById(R.id.btn_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                        39d43f82cb273e9fa8059dc4
                poiSearch.searchPoiDetail(new PoiDetailSearchOption().poiUids("39d43f82cb273e9fa8059dc4"));
            }
        });


        findViewById(R.id.btn_3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                poiSearch.searchNearby(new PoiNearbySearchOption().location(mLatLng).radius(2000).keyword("学校"));
            }
        });

        findViewById(R.id.btn_4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LatLng leftTop =new LatLng(mLatLng.latitude+0.05,mLatLng.longitude-0.05);
                LatLng rightBottom =new LatLng(mLatLng.latitude-0.05,mLatLng.longitude+0.05);
                LatLngBounds latLngBounds=new LatLngBounds.Builder().include(leftTop).include(rightBottom).build();
                poiSearch.searchInBound(new PoiBoundSearchOption().bound(latLngBounds).keyword("美食"));
            }
        });


        mMapView.getMap().setMapType(BaiduMap.MAP_TYPE_NORMAL);
        //开启交通图
        mMapView.getMap().setTrafficEnabled(true);
        //开启热力图
          mMapView.getMap().setBaiduHeatMapEnabled(false);

        mMapView.getMap().setMyLocationEnabled(true);

        mMapView.setLogoPosition(LogoPosition.logoPostionleftTop);


        //实例化UiSettings类对象
        UiSettings  mUiSettings = mMapView.getMap().getUiSettings();
        //通过设置enable为true或false 选择是否显示指南针
        mUiSettings.setCompassEnabled(true);

        //通过设置enable为true或false 选择是否显示比例尺
        mMapView.showScaleControl(false);

        //通过设置enable为true或false 选择是否显示缩放按钮
        mMapView.showZoomControls(true);

        initLocationClient();

        MyLocationConfiguration myLocationConfiguration=new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING,true, BitmapDescriptorFactory.fromResource(android.R.mipmap.sym_def_app_icon),0xAAFFFF88,0xAA00FF00);

        mMapView.getMap().setMyLocationConfiguration(myLocationConfiguration);
    }

    private void drawText(LatLng latLng) {

        //文字覆盖物位置坐标
        LatLng llText = latLng;

        //构建TextOptions对象
        OverlayOptions mTextOptions = new TextOptions()
                .text("中国领土不可侵犯") //文字内容
                .bgColor(0xAAFFFF00) //背景色
                .fontSize(24) //字号
                .fontColor(0xFFFF00FF) //文字颜色
                .rotate(0) //旋转角度
                .position(llText);

        //在地图上显示文字覆盖物
        Overlay mText = mMapView.getMap().addOverlay(mTextOptions);
    }

    private void drawCircle(LatLng latLng) {

        //圆心位置
        LatLng center = latLng;

        //构造CircleOptions对象
        CircleOptions mCircleOptions = new CircleOptions().center(center)
                .radius(200)
                .fillColor(0xAA0000FF) //填充颜色
                .stroke(new Stroke(5, 0xAA00ff00)); //边框宽和边框颜色

        //在地图上显示圆
        Overlay mCircle = mMapView.getMap().addOverlay(mCircleOptions);
    }

    private void initLocationClient(){
        //定位初始化
        mLocationClient = new LocationClient(this);

//通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);

        //设置locationClientOption
        mLocationClient.setLocOption(option);

        //注册LocationListener监听器
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        //开启地图定位图层
        mLocationClient.start();
    }

    private void showInfoWindow(LatLng latLng){
        //用来构造InfoWindow的Button
        Button button = new Button(getApplicationContext());
        button.setBackgroundResource(R.drawable.redbg);
        button.setText("此生不悔入华夏");

        //构造InfoWindow
        //point 描述的位置点
        //-100 InfoWindow相对于point在y轴的偏移量
        InfoWindow mInfoWindow = new InfoWindow(button, latLng, -100);

        //使InfoWindow生效
        mMapView.getMap().showInfoWindow(mInfoWindow);
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mLocationClient.stop();
        mMapView.getMap().setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null){
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();

            mMapView.getMap().setMyLocationData(locData);
        }
    }
}
